import axios from 'axios'
import { Message } from 'element-ui'
import { tansParams } from "@/utils/common";
import router from '../router'

const duration = 5 * 1000; // 消息显示时间
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60 * 1000
})
let tips = null; // 消息提示

// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = config.headers.isToken === false
  let token = localStorage.getItem('token')
  if (token && !isToken) {
    config.headers['token'] = token
  }
  if (config.method === 'get' && config.params) {
    config.url += '?' + tansParams(config.params).slice(0, -1);
    config.params = {};
  }
  return config
}, error => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    const code = res.status || 200;
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      router.replace({ path: '/login' });
      MsgInfo( '登录已过期，请重新登录。', 'error');
      return Promise.reject()
    }
    if (res.data && res.data.code !== 1) {
      MsgInfo( res.data.msg || '服务异常，请稍后再试', 'error');
      return res.data
    }
    return res.data || {}
  },
  error => {
    let { message } = error;
    if (message === "Network Error") {
      message = "网络异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      let code = message.substr(message.length - 3);
      if (code == 401) {
        message = "登录已过期，请重新登录。";
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        router.replace({ path: '/login' });
      } else if (code == 404) {
        message = "系统接口请求资源不存在";
      } else if (code == 403) {
        message = "系统接口无访问权限";
      } else if (code == 500) {
        message = "系统接口内部错误";
      } else {
        message = `系统接口${code}异常`;
      }
    }
    MsgInfo( message, 'error');
  }
)

// 消息提示
function MsgInfo(message, type) {
  if (tips) tips.close()
  tips = Message({ message, type, duration });
}

export default service
